# Import modules
import pygame
import sys
import easygui
import tkinter
import json
import random
import time
from pygame.locals import *
from Crypto.Cipher import AES

# Set all Tk windows into one icon
temproot = tkinter.Tk()
temproot.iconphoto(True, tkinter.PhotoImage(file="icons/card.png"))
temproot.withdraw()

# Get Username and Password
username = easygui.enterbox("请输入你的用户名：", "七三班大作战")
if not username:
    easygui.msgbox("您未输入用户名，请再次尝试。", "七三班大作战")
    sys.exit()

# Init of PyGame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("七三班大作战")

# Get surfaces
i_card = pygame.image.load("icons/card.png")
i_coin = pygame.image.load("icons/coin.png")
pygame.display.set_icon(i_card)
background = pygame.image.load("images/background.jpg")
background1 = pygame.image.load("images/charinfo.jpg")
title = pygame.font.Font("fonts/font-1.ttf", 60).render("七三班 大作战", True, (0, 0, 0))
t_user = pygame.font.Font("fonts/font-2.ttf", 30).render("Hi, "+username, True, (0, 0, 0))
steve = pygame.image.load("icons/steve.png")
duck = pygame.image.load("icons/duck.png")
sun = pygame.image.load("icons/sun.png")
card_start = pygame.image.load("icons/card-start.png")
left = pygame.image.load("icons/left.png")
right = pygame.image.load("icons/right.png")
back = pygame.image.load("icons/back.png")
left_rect = pygame.Rect(250, 100, 100, 100)
right_rect = pygame.Rect(450, 100, 100, 100)
back_rect = pygame.Rect(25, 25, 50, 50)
i_life = pygame.image.load("icons/life.png")
i_attack = pygame.image.load("icons/attack.png")
i_defense = pygame.image.load("icons/defense.png")

# Variables
n_card = 10
n_coin = 0
char_num = dict.fromkeys(range(21, 42), 0)
mode = 0
char_page = 21
card_id = 0
fea1_rect = pygame.Rect(100, 300, 200, 50)
fea2_rect = pygame.Rect(500, 300, 200, 50)
fea3_rect = pygame.Rect(100, 400, 200, 50)
fea4_rect = pygame.Rect(500, 400, 200, 50)
fea1_on = False
fea2_on = False
fea3_on = False
fea4_on = False
ck1_rect = pygame.Rect(100, 400, 200, 50)
ck2_rect = pygame.Rect(500, 400, 200, 50)
ck1_on = False
ck2_on = False

# Functions
def coloron(ison):
    if ison:
        return (200, 0, 0)
    else:
        return (255, 0, 0)

def save():
    dic = {
        'username': username,
        'n_card': n_card,
        'n_coin': n_coin,
        'characters': char_num
    }
    do_crypt = easygui.ccbox(msg='是否加密存档？', title='七三班大作战', choices=('加密', '不加密'), image=None)
    if do_crypt:
        filename = easygui.filesavebox(default="*.aes")
        if not filename:
            easygui.msgbox("请选择保存位置，请再次尝试。", "七三班大作战")
            return
        if not filename.lower().endswith(".aes"):
            filename += ".aes"
        print(filename)
        filename = 'data-{}.aes'.format(int(time.time()))
        password = easygui.enterbox("请输入加密密码：", "七三班大作战")
        if not password:
            easygui.msgbox("您未输入密码，请再次尝试。", "七三班大作战")
            return
        password = password.encode()
        while len(password) % 16 != 0:
            password += b'\x00'
        text = json.dumps(dic, separators=(',', ':'), ensure_ascii=False)
        text = text.encode()
        while len(text) % 16 != 0:
            text += b'\x00'
        model = AES.MODE_ECB
        aes = AES.new(password, model)
        encrypt_text = aes.encrypt(text)
        with open(filename, 'wb') as f:
            f.write(encrypt_text)
    else:
        filename = easygui.filesavebox(default="*.json")
        if not filename:
            easygui.msgbox("请选择保存位置，请再次尝试。", "七三班大作战")
            return
        if not filename.lower().endswith(".json"):
            filename += ".json"
        with open(filename, 'w') as f:
            json.dump(dic, f, separators=(',', ':'))
    easygui.msgbox("存档已保存到 {}".format(filename), "七三班大作战")

def load():
    global username, n_card, n_coin, char_num
    path = easygui.fileopenbox()
    if not path:
        easygui.msgbox("您未选择文件，请再次尝试。", "七三班大作战")
        return
    if path.lower().endswith(".aes"):
        with open(path, 'rb') as f:
            content = f.read()
        password = easygui.enterbox("检测到加密文件，请输入加密密码：", "七三班大作战")
        if not password:
            easygui.msgbox("您未输入密码，请再次尝试。", "七三班大作战")
            return
        password = password.encode()
        while len(password) % 16 != 0:
            password += b'\x00'
        model = AES.MODE_ECB
        aes = AES.new(password, model)
        try:
            decrypt_text = aes.decrypt(content).decode().strip('\0')
            file = json.loads(decrypt_text)
        except:
            easygui.msgbox("密码错误，请再次尝试。", "七三班大作战")
            return
    else:
        with open(path) as f:
            file = json.load(f)
    username = file['username']
    n_card = file['n_card']
    n_coin = file['n_coin']
    char_num = {}
    for key in file['characters']:
        char_num[int(key)] = file['characters'][key]
    easygui.msgbox("导入成功", "七三班大作战")

def loadjson(filename):
    dic = json.load(open(filename))
    ret = {}
    for i, j in dic.items():
        ret[int(i)] = j
    return ret
def savejson(obj, filename):
    json.dump(obj, open(filename, 'w'), separators=(',', ':'), ensure_ascii=False)

character_names = loadjson("data/names.json")
character_max_life = loadjson("data/max_life.json")
character_attack = loadjson("data/attack.json")
character_defense = loadjson("data/defense.json")
character_possibility = loadjson("data/possibility.json")
# Game Loop
while True:
    for event in pygame.event.get():
        # Events
        if event.type == QUIT:
            # Exit Game
            pygame.quit()
            sys.exit()
        if event.type == MOUSEMOTION:
            if mode == 0:
                fea1_on = bool(fea1_rect.collidepoint(event.pos))
                fea2_on = bool(fea2_rect.collidepoint(event.pos))
                fea3_on = bool(fea3_rect.collidepoint(event.pos))
                fea4_on = bool(fea4_rect.collidepoint(event.pos))
            if mode == 2:
                ck1_on = bool(ck1_rect.collidepoint(event.pos))
                ck2_on = bool(ck2_rect.collidepoint(event.pos))
        if event.type == MOUSEBUTTONDOWN:
            if mode == 0:
                if fea1_rect.collidepoint(event.pos):
                    save()
                if fea2_rect.collidepoint(event.pos):
                    load()
                if fea3_rect.collidepoint(event.pos):
                    mode = 1
                    continue
                if fea4_rect.collidepoint(event.pos):
                    mode = 2
                    continue
            if mode == 1:
                if left_rect.collidepoint(event.pos):
                    if char_page == 21:
                        char_page = 40
                    else:
                        char_page -= 1
                if right_rect.collidepoint(event.pos):
                    if char_page == 40:
                        char_page = 21
                    else:
                        char_page += 1
                if back_rect.collidepoint(event.pos):
                    mode = 0
            if mode == 2:
                if back_rect.collidepoint(event.pos):
                    mode = 0
                if ck1_rect.collidepoint(event.pos):
                    if n_card == 0:
                        easygui.msgbox("你没卡了！", "七三班大作战")
                        continue
                    else:
                        n_card -= 1
                    lis = []
                    for i, j in character_possibility.items():
                        for k in range(j):
                            lis.append(i)
                    ans = random.choice(lis)
                    card_id = ans
                    char_num[ans] += 1
                if ck2_rect.collidepoint(event.pos):
                    if n_coin < 5:
                        easygui.msgbox("你没币了！", "七三班大作战")
                        continue
                    else:
                        n_coin -= 5
                    lis = []
                    for i, j in character_possibility.items():
                        for k in range(j):
                            lis.append(i)
                    ans = random.choice(lis)
                    card_id = ans
                    char_num[ans] += 1
        if event.type == KEYDOWN:
            if mode == 1:
                if event.key == K_LEFT or event.key == K_PAGEUP:
                    if char_page == 21:
                        char_page = 40
                    else:
                        char_page -= 1
                if event.key == K_RIGHT or event.key == K_PAGEDOWN:
                    if char_page == 40:
                        char_page = 21
                    else:
                        char_page += 1
                if event.key == K_ESCAPE or event.key == K_HOME:
                    mode = 0
            if mode == 2:
                if event.key == K_ESCAPE or event.key == K_HOME:
                    card_id = 0
                    mode = 0
    if mode == 0:
        screen.blit(background, (0, 0))
        screen.blit(title, (220, 180))
        sn_card = pygame.font.SysFont("Consolas", 40).render(str(n_card), True, (0, 0, 0))
        sn_coin = pygame.font.SysFont("Consolas", 40).render(str(n_coin), True, (0, 0, 0))
        screen.blit(t_user, (20, 20))
        screen.blit(i_card, (200, 20))
        screen.blit(i_card, (200, 20))
        screen.blit(i_coin, (500, 20))
        screen.blit(sn_card, (300, 25))
        screen.blit(sn_coin, (600, 25))
        pygame.draw.rect(screen, coloron(fea1_on), fea1_rect)
        pygame.draw.rect(screen, coloron(fea2_on), fea2_rect)
        pygame.draw.rect(screen, coloron(fea3_on), fea3_rect)
        pygame.draw.rect(screen, coloron(fea4_on), fea4_rect)
        fea1_word = pygame.font.Font("fonts/font-2.ttf", 30).render("存档", True, (0, 0, 0))
        fea2_word = pygame.font.Font("fonts/font-2.ttf", 30).render("加载存档", True, (0, 0, 0))
        fea3_word = pygame.font.Font("fonts/font-2.ttf", 30).render("角色信息", True, (0, 0, 0))
        fea4_word = pygame.font.Font("fonts/font-2.ttf", 30).render("每日抽卡", True, (0, 0, 0))
        screen.blit(fea1_word, (170, 300))
        screen.blit(fea2_word, (540, 300))
        screen.blit(fea3_word, (140, 400))
        screen.blit(fea4_word, (540, 400))

    if mode == 1:
        screen.blit(background1, (0, 0))
        if char_page == 22:
            screen.blit(duck, (350, 100))
        elif char_page == 32:
            screen.blit(sun, (350, 100))
        else:
            screen.blit(steve, (350, 100))
        char_name = pygame.font.Font("fonts/font-3.ttf", 50).render(character_names[char_page], True, (255, 255, 255))
        char_id = pygame.font.Font("fonts/font-4.ttf", 35).render("No. {}".format(char_page), True, (255, 255, 255))
        you_have = pygame.font.Font("fonts/font-4.ttf", 20).render("You have: {}".format(char_num[char_page]), True, (255, 255, 255))
        screen.blit(char_name, (400 - char_name.get_rect().width / 2, 225))
        screen.blit(char_id, (400 - char_id.get_rect().width / 2, 275))
        screen.blit(you_have, (400 - you_have.get_rect().width / 2, 325))
        screen.blit(left, left_rect)
        screen.blit(right, right_rect)
        screen.blit(back, back_rect)
        for i in range(character_max_life[char_page]):
            screen.blit(i_life, (100 + i * 20, 375))
        for i in range(character_attack[char_page]):
            screen.blit(i_attack, (400 + i * 20, 375))
        for i in range(character_defense[char_page]):
            screen.blit(i_defense, (600 + i * 20, 375))

    if mode == 2:
        screen.blit(background1, (0, 0))
        sn_card = pygame.font.SysFont("Consolas", 40).render(str(n_card), True, (255, 255, 255))
        sn_coin = pygame.font.SysFont("Consolas", 40).render(str(n_coin), True, (255, 255, 255))
        screen.blit(i_card, (200, 20))
        screen.blit(i_coin, (500, 20))
        screen.blit(sn_card, (300, 25))
        screen.blit(sn_coin, (600, 25))
        screen.blit(back, back_rect)
        pygame.draw.rect(screen, coloron(ck1_on), ck1_rect)
        pygame.draw.rect(screen, coloron(ck2_on), ck2_rect)
        num_1 = pygame.font.Font("fonts/font-2.ttf", 30).render(" × 1", True, (0, 0, 0))
        num_5 = pygame.font.Font("fonts/font-2.ttf", 30).render(" × 5", True, (0, 0, 0))
        screen.blit(i_card, (150, 400))
        screen.blit(i_coin, (550, 400))
        screen.blit(num_1, (200, 400))
        screen.blit(num_5, (600, 400))
        if card_id:
            if card_id == 22:
                screen.blit(duck, (350, 100))
            elif card_id == 32:
                screen.blit(sun, (350, 100))
            else:
                screen.blit(steve, (350, 100))
            char_name = pygame.font.Font("fonts/font-3.ttf", 50).render(character_names[card_id], True, (255, 255, 255))
            char_id = pygame.font.Font("fonts/font-4.ttf", 35).render("No. {}".format(card_id), True, (255, 255, 255))
            you_have = pygame.font.Font("fonts/font-4.ttf", 20).render("You have: {}".format(char_num[card_id]), True, (255, 255, 255))
            screen.blit(char_name, (400 - char_name.get_rect().width / 2, 225))
            screen.blit(char_id, (400 - char_id.get_rect().width / 2, 275))
            screen.blit(you_have, (400 - you_have.get_rect().width / 2, 325))
        else:
            screen.blit(card_start, (350, 100))
            card_info = pygame.font.Font("fonts/font-3.ttf", 50).render("请点击相应按键抽卡", True, (255, 255, 255))
            screen.blit(card_info, (400 - card_info.get_rect().width / 2, 225))
    pygame.display.flip()